<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\GoodsAttr;
use think\Db;
/**
 * 商品列管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{
    
    /**
     * Goods模型对象
     * @var \app\common\model\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Goods;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['category'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','image','name','createtime','price']);
                $row->visible(['category']);
				$row->getRelation('category')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if(empty($params['attr'])){
                    $this->error('请添加规格');
                }
                //商品规格
                $goods_attr = $params['attr'];
                $price_list = array_column($goods_attr,'price');
                sort($price_list);
                $params['price'] = $price_list[0];
                unset($params['attr']);
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['createtime'] = time();
                    $result = $this->model->allowField(true)->insertGetId($params);
                    if($result){
                        foreach($goods_attr as &$value){
                            $value['goods_id'] = $result;
                            $value['createtime'] = time();
                        }
                        $res1 = GoodsAttr::insertAll($goods_attr);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false && $res1) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $attr = json_decode($params['attr'],true);
                if(empty($attr)){
                    $this->error('请添加规格');
                }
                $price_list = array_column($attr,'price');
                sort($price_list);
                $params['price'] = $price_list[0];
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    foreach($attr as &$value){
                        if($value['id']){
                            GoodsAttr::where('id',$value['id'])->update($value);
                        }else{
                            $value['goods_id'] = $row['id'];
                            GoodsAttr::create($value);
                        }
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $goods_attr =GoodsAttr::where('goods_id',$row['id'])->select();
        $goods_attr1 = array();
        foreach($goods_attr as  $key=>$value){
            $goods_attr1[$key]['attr_name'] = $value['attr_name'];
            $goods_attr1[$key]['price'] = $value['price'];
            $goods_attr1[$key]['share_num'] = $value['share_num'];
            $goods_attr1[$key]['tableware_num'] = $value['tableware_num'];
        }
        $goods_attr = json_encode($goods_attr,true);
        $this->view->assign("row", $row);
        $this->view->assign("goods_attr", $goods_attr);
        return $this->view->fetch();
    }
    public function del_attr($id){
        if ($id) {
            Db::startTrans();
            try {
                $res = GoodsAttr::where('id',$id)->delete();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($res){
                $arr = array('code'=>200,'msg'=>'删除成功');
            }else{
                $arr = array('code'=>400,'msg'=>'删除失败');
            }
        }else{
            $arr = array('code'=>400,'msg'=>'数据异常');
        }
        return json($arr);
    }
}
